import vscode, { languages, TextDocument, Position, CancellationToken, ExtensionContext, CompletionContext } from 'vscode';
import { getBasePath } from 'src/util';
import config from 'src/config';

/**
 * 自动提示实现
 * @param document 
 * @param position 
 * @param token 
 * @param context 
 */
function provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken, context: CompletionContext) {
  const line = document.lineAt(position);
  const projectPath = getBasePath(document);

  // 只截取到光标位置为止，防止一些特殊情况
  const lineText = line.text.substring(0, position.character);
  // 简单匹配，只要当前光标前的字符串为`this.dependencies.`都自动带出所有的依赖
  if (/(^|=| )\w+\.dependencies\.$/g.test(lineText)) {
    const json = require(`${projectPath}/package.json`);
    const dependencies = Object.keys(json.dependencies || {}).concat(Object.keys(json.devDependencies || {}));
    return dependencies.map(dep => {
      // vscode.CompletionItemKind 表示提示的类型
      return new vscode.CompletionItem(dep, vscode.CompletionItemKind.Field);
    })
  }
}

/**
 * 注册标签智能提示
 * @param context 
 */
export default function registerTagCompletion(context: ExtensionContext) {
  // 注册代码建议提示，只有当按下“.”时才触发
  context.subscriptions.push(languages.registerCompletionItemProvider(config.xmlSuffix, {
    provideCompletionItems
  }, '<'));
};